package pl.enigmatic.util;

import java.util.ArrayList;


public class Java {

	public static final String UNDERLINE = "_";

	private Java() {}

	public static String[] split(final String name) {
		final ArrayList<String> res = new ArrayList<String>();
		int lower = 0;
		final char[] split = Strings.getChars(name);
		for (int i = 0; i < split.length; i++) {
			if (Character.isLowerCase(split[i]) && (i == split.length - 1 || Character.isUpperCase(split[i + 1]))) {
				res.add(name.substring(lower, i + 1));
				lower = i + 1;
			} else if (Character.isUpperCase(split[i]) && i < split.length - 1 && Character.isLowerCase(split[i + 1]) && i > 0
					&& Character.isUpperCase(split[i - 1])) {
				res.add(name.substring(lower, i));
				lower = i;
			}
		}
		if (lower < split.length) {
			res.add(name.substring(lower, split.length));
		}
		return res.toArray(new String[res.size()]);
	}

	public static String convertJavaStyleToConstantName(final String name) {
		return Strings.concatenate(UNDERLINE, Strings.toUpperCase(Java.split(name)));
	}

	public static String convertConstantNameToJavaStyle(String name) {
		final String[] split = name.toLowerCase().split(UNDERLINE);
		StringBuilder builder = new StringBuilder();
		builder.append(split[0]);
		for (int i = 1; i < split.length; i++) {
			builder.append(Strings.firstUpper(split[i]));
		}
		return builder.toString();
	}

}
